<template>
  <div class="diagnostic-container">
    <h1>注册问题诊断</h1>

    <!-- 环境检查 -->
    <div class="section">
      <h2>环境检查</h2>
      <div class="check-item">
        <strong>Supabase URL:</strong>
        <span :class="supabaseUrl ? 'success' : 'error'">
          {{ supabaseUrl || '未配置' }}
        </span>
      </div>
      <div class="check-item">
        <strong>Supabase Key:</strong>
        <span :class="supabaseKey ? 'success' : 'error'">
          {{ supabaseKey ? '已配置' : '未配置' }}
        </span>
      </div>
    </div>

    <!-- 数据库连接测试 -->
    <div class="section">
      <h2>数据库连接测试</h2>
      <button @click="testConnection" :disabled="testing">测试连接</button>
      <div v-if="connectionResult">
        <pre>{{ JSON.stringify(connectionResult, null, 2) }}</pre>
      </div>
    </div>

    <!-- 表结构检查 -->
    <div class="section">
      <h2>表结构检查</h2>
      <button @click="checkTables" :disabled="testing">检查表结构</button>
      <div v-if="tablesResult">
        <pre>{{ JSON.stringify(tablesResult, null, 2) }}</pre>
      </div>
    </div>

    <!-- 测试注册 -->
    <div class="section">
      <h2>测试注册</h2>
      <el-form :model="testForm" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="testForm.username" placeholder="测试用户名" />
        </el-form-item>
        <el-form-item label="姓名">
          <el-input v-model="testForm.name" placeholder="测试姓名" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="testForm.email" placeholder="test@example.com" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="testForm.phone" placeholder="13800138000" />
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="testForm.password" type="password" placeholder="123456" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="testRegister" :disabled="testing"> 测试注册 </el-button>
        </el-form-item>
      </el-form>
      <div v-if="registerResult">
        <h3>注册结果:</h3>
        <pre>{{ JSON.stringify(registerResult, null, 2) }}</pre>
      </div>
    </div>

    <!-- 详细错误日志 -->
    <div class="section">
      <h2>详细错误日志</h2>
      <div v-if="errorLogs.length">
        <div v-for="(log, index) in errorLogs" :key="index" class="error-log">
          <strong>{{ log.timestamp }}:</strong> {{ log.message }}
          <pre v-if="log.details">{{ JSON.stringify(log.details, null, 2) }}</pre>
        </div>
      </div>
      <div v-else>暂无错误日志</div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { supabase } from '@/lib/supabase'
import { useUserStore } from '@/stores/user'

const userStore = useUserStore()

// 环境变量
const supabaseUrl = ref('')
const supabaseKey = ref('')

// 测试状态
const testing = ref(false)
const connectionResult = ref(null)
const tablesResult = ref(null)
const registerResult = ref(null)
const errorLogs = ref([])

// 测试表单
const testForm = ref({
  username: 'testuser' + Date.now(),
  name: '测试用户',
  email: 'test' + Date.now() + '@example.com',
  phone: '13800138000',
  password: '123456',
})

// 添加错误日志
const addErrorLog = (message, details = null) => {
  errorLogs.value.unshift({
    timestamp: new Date().toLocaleString(),
    message,
    details,
  })
}

// 测试连接
const testConnection = async () => {
  testing.value = true
  try {
    const { data, error } = await supabase.from('courts').select('count').limit(1)
    if (error) {
      connectionResult.value = { success: false, error: error.message }
      addErrorLog('数据库连接失败', error)
    } else {
      connectionResult.value = { success: true, message: '连接成功' }
    }
  } catch (error) {
    connectionResult.value = { success: false, error: error.message }
    addErrorLog('连接测试异常', error)
  } finally {
    testing.value = false
  }
}

// 检查表结构
const checkTables = async () => {
  testing.value = true
  try {
    const tables = ['users', 'courts', 'time_slots', 'bookings']
    const results = {}

    for (const table of tables) {
      try {
        const { data, error } = await supabase.from(table).select('*').limit(1)
        if (error) {
          results[table] = { exists: false, error: error.message }
          addErrorLog(`表 ${table} 检查失败`, error)
        } else {
          results[table] = { exists: true, count: data?.length || 0 }
        }
      } catch (error) {
        results[table] = { exists: false, error: error.message }
        addErrorLog(`表 ${table} 检查异常`, error)
      }
    }

    tablesResult.value = results
  } catch (error) {
    tablesResult.value = { error: error.message }
    addErrorLog('表结构检查异常', error)
  } finally {
    testing.value = false
  }
}

// 测试注册
const testRegister = async () => {
  testing.value = true
  try {
    const result = await userStore.register(testForm.value)
    registerResult.value = result

    if (!result.success) {
      addErrorLog('注册测试失败', result)
    }
  } catch (error) {
    registerResult.value = { success: false, error: error.message }
    addErrorLog('注册测试异常', error)
  } finally {
    testing.value = false
  }
}

onMounted(() => {
  // 获取环境变量
  supabaseUrl.value = import.meta.env.VITE_SUPABASE_URL || ''
  supabaseKey.value = import.meta.env.VITE_SUPABASE_ANON_KEY ? '已配置' : '未配置'
})
</script>

<style scoped>
.diagnostic-container {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.check-item {
  margin-bottom: 10px;
}

.success {
  color: #67c23a;
}

.error {
  color: #f56c6c;
}

pre {
  background-color: #f4f4f4;
  padding: 10px;
  border-radius: 5px;
  overflow-x: auto;
  font-size: 12px;
  max-height: 300px;
  overflow-y: auto;
}

.error-log {
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fef0f0;
  border-left: 4px solid #f56c6c;
  border-radius: 4px;
}

button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  cursor: pointer;
  margin-right: 10px;
}

button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

button:hover:not(:disabled) {
  background-color: #0056b3;
}
</style>
